#include"stack.h"
void STPush(ST* pst, StackDatatype x)
{
	assert(pst);
	pst->Top++;
	if (pst->Top == pst->capacity)
	{
		int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
		StackDatatype* tmp = (StackDatatype*)realloc(pst->data, sizeof(StackDatatype) * newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			return;
		}

		pst->data = tmp;
		pst->capacity = newcapacity;
	}
	
	pst->data[pst->Top] = x;
	
}
void StackInit(ST* pst)
{
	assert(pst);
	pst->capacity = 0;
	pst->data = NULL;
	pst->Top = -1;
}
void JudgeCapacity(ST* pst)
{
	assert(pst);
	if (pst->capacity == pst->Top)
	{
		int newcapacity = pst->capacity == 0 ? 4 : 2 * pst->capacity;
		StackDatatype* tmp = (StackDatatype*)realloc(pst->data, sizeof(StackDatatype) * newcapacity);
		if (tmp == NULL)
		{
			perror("malloc failed!");
			return;
		}
		pst->data = tmp;
		pst->capacity = newcapacity;
	}
	
}

void Push(ST* pst, StackDatatype x)
{
	assert(pst);
	pst->Top++;
	JudgeCapacity(pst);
	
	pst->data[pst->Top] = x;
}
void Pop(ST* pst)
{
	assert(pst);
	assert(pst->Top > -1);
	pst->Top--;
}
StackDatatype StackTop(ST* pst)
{
	assert(pst);
	return pst->data[pst->Top];
}
int StackSize(ST* pst)
{
	assert(pst);
	return pst->Top+1;
}
bool StackEmpty(ST* pst)
{
	assert(pst);
	return pst->Top == -1;
}
void StackDestroy(ST* pst)
{
	assert(pst);
	free(pst->data);
	pst->data = NULL;
	pst->capacity = 0;
	pst->Top = -1;
}